/* 
 * Copyright 2009 Kazuhiro Sera. 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language 
 * governing permissions and limitations under the License. 
 */

package org.lightdi.util;

import java.lang.reflect.Constructor;

import org.lightdi.constant.LightDIConstant;

/**
 * ReflectUtil<br>
 * <br>
 * 
 * @author Kazuhiro Sera
 * @version 1.0
 */

public class ReflectionUtil {

	public static String getSetterMethodName(String fieldName) {
		if (fieldName == null || "".equals(fieldName))
			throw new IllegalArgumentException("Illegal field name");
		// remove double quote
		fieldName = fieldName.replaceAll(LightDIConstant.DOUBLE_QUOTE,
				LightDIConstant.EMPTY);
		String replacedFirstChar = fieldName.substring(0, 1).toUpperCase();
		return "set" + replacedFirstChar + fieldName.substring(1);
	}

	public static String getGetterMethodName(String fieldName) {
		if (fieldName == null || "".equals(fieldName))
			throw new IllegalArgumentException("Illegal field name");
		// remove double quote
		fieldName = fieldName.replaceAll(LightDIConstant.DOUBLE_QUOTE,
				LightDIConstant.EMPTY);
		String replacedFirstChar = fieldName.substring(0, 1).toUpperCase();
		return "get" + replacedFirstChar + fieldName.substring(1);
	}

	@SuppressWarnings("unchecked")
	public static <T> T instantiate(Class<?> clazz, Object... args) {
		T ret = null;
		Constructor<?>[] constructors = clazz.getDeclaredConstructors();
		for (Constructor<?> constructor : constructors) {
			try {
				ret = (T) constructor.newInstance(args);
				break;
			} catch (Exception ignore) {
			}
		}
		return ret;
	}

}
